package com.hopes.bizz.risk.hid.listener;

/**
 * @author: ljh
 * @create: 2023/6/29
 */


import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.Units;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;


@Slf4j
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ImageModifyHandler implements CellWriteHandler {


    // 图片字节数组
    private HashMap<String, List<byte[]>> images;


    // 每列图片的最大个数
    private HashMap<Integer,Integer> columnImageMostCount;

    /**
     * 数据转换完成后
     *
     * @param writeSheetHolder
     * @param writeTableHolder
     * @param cellData
     * @param cell
     * @param head
     * @param relativeRowIndex
     * @param isHead
     */
    @Override
    public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, WriteCellData<?> cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        // 此处不处理表头，不处理不包含图像的
        boolean noImageValue = Objects.isNull(cellData) ||
                CollectionUtils.isEmpty(cellData.getImageDataList());
        if (Objects.equals(Boolean.TRUE, isHead) || noImageValue) {
            return;
        }
        cellData.setType(CellDataTypeEnum.EMPTY);
    }


    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        // 在 单元格写入完毕后 ，自己填充图片
        int rowIndex = cell.getRowIndex();
        int columnIndex = cell.getColumnIndex();

        //指定单元格自己渲染图片
        for (String position : images.keySet()) {
            int row = Integer.parseInt(position.split(",")[0]);
            int column = Integer.parseInt(position.split(",")[1]);
            if (rowIndex == row && column == columnIndex ) {
                Sheet sheet = cell.getSheet();
                List<byte[]> bytes = images.get(position);
                //每张图片的宽度
                int picWidth = Units.pixelToEMU(80);
                //列宽设置为图片的总宽度---不设置宽度，当图片的坐标超过单元格宽度时图片显示失败
                //EMU转字符宽度：characterWidth = emu / 256
                sheet.setColumnWidth(columnIndex, picWidth * columnImageMostCount.get(column) / 290);
                for (int i = 0; i < bytes.size(); i++) {
                    int index = sheet.getWorkbook().addPicture(bytes.get(i), HSSFWorkbook.PICTURE_TYPE_JPEG);
                    Drawing drawing = sheet.getDrawingPatriarch();
                    if (drawing == null) {
                        drawing = sheet.createDrawingPatriarch();
                    }
                    CreationHelper helper = sheet.getWorkbook().getCreationHelper();
                    ClientAnchor anchor = helper.createClientAnchor();
                    // 设置图片坐标
                    anchor.setDx1(picWidth * i);
                    anchor.setDx2(picWidth * (1 + i));
                    anchor.setDy1(0);
                    anchor.setDy2(0);
                    //设置图片位置
                    anchor.setCol1(cell.getColumnIndex());
                    anchor.setCol2(cell.getColumnIndex());
                    anchor.setRow1(cell.getRowIndex());
                    anchor.setRow2(cell.getRowIndex() + 1);
                    // 设置图片可以随着单元格移动
                    anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
                    drawing.createPicture(anchor, index);
                }
            }
        }

    }


}

